import json
import time
from datetime import datetime, timedelta

import requests
from django.db import models
from django.http import JsonResponse
from django.shortcuts import render
import jwt
from jwt import ExpiredSignatureError

from common.models import User
from common.utils import openid_to_uid

# 随机的salt密钥，只有token生成者（同时也是校验者）自己能有，用于校验生成的token是否合法
salt = "SECRET_KEY_123456"


# token合法性校验
def check_login(request):
    token = request.GET.get("token")

    try:
        info = jwt.decode(token, salt, algorithms='HS256')
        exp = int(info.pop('exp'))
        print(exp)
        code = '200'
        msg = "token is valid"
        c_data = True
        if time.time() > exp:
            code = '401'
            msg = "signature has expired"
            c_data = False
        # if (info):
        #     code = '200'
        #     msg = "token is valid"
    except (ExpiredSignatureError, jwt.DecodeError, jwt.InvalidTokenError, AttributeError, Exception) as e:
        code = '400'
        msg = str(e)
        c_data = False
        # print(e)

    return JsonResponse({
        "code": code,
        "msg": msg,
        "data": c_data
    })


# 登录
def login(request):
    if request.method == "POST":
        login_code = request.POST.get("login_code")
        login_type = request.POST.get("login_type")

        # 小程序登录凭证校验,https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
        params = {'appid': 'wx6831a39818855152', 'secret': "6055139e57b41dc062f76e8bae79ac89",
                  'js_code': login_code, 'grant_type': 'authorization_code'}
        response = requests.get("https://api.weixin.qq.com/sns/jscode2session", params)

        session = response.json()
        # print(session)
        openid = session.get("openid")

        # noinspection PyBroadException
        try:
            # openid 当做用户的uid
            user = User.objects.get(uid=openid)
            print("get new user:" + str(user))
        except:
            user = User.objects.create_user(username=openid, password="123456", is_lawyer=(login_type == "lawyer"))
            print("create new user:" + str(user))

        userinfo = {
            # uid返回给前端，需要加密
            "uid": openid_to_uid(user.uid),
            "nickname": user.nickname,
            "avatar_url": user.avatar
        }

        # 设置headers，即加密算法的配置
        headers = {
            "alg": "HS256",
            "typ": "JWT"
        }

        payload = {
            # 公共声明
            'exp': datetime.now() + timedelta(minutes=3000),  # (Expiration Time) 令牌过期时间
            'iat': time.time(),  # (Issued At) 指明此创建时间的时间戳
            # 私有声明  想要传递的信息
            'session': session
        }

        token = jwt.encode(payload, salt, algorithm='HS256', headers=headers)

        return JsonResponse({
            "code": login_code,
            "msg": "success",
            "data": {"token": token, "userinfo": userinfo}
        })
    else:
        return render(request, "method is wrong")
